#include "AuthManager.h"
#include <QRegularExpression>
#include <QSettings>
#include <QStandardPaths>
#include <QDir>
#include <QDebug>

AuthManager::AuthManager(QObject *parent) 
    : QObject(parent), m_isLoggedIn(false), m_userId(-1), m_isAdmin(false)
{
    dbManager = new DatabaseManager(this);
    
    // 连接数据库并初始化用户表
    if (dbManager->connectToDB()) {
        dbManager->initializeUserTable();
        // 加载之前保存的登录状态
        loadLoginState();
    } else {
        qFatal("数据库连接失败，程序终止！");
    }
}

AuthManager::~AuthManager()
{
    delete dbManager;
}

bool AuthManager::registerUser(const QString &username, const QString &email, const QString &password)
{
    qDebug() << "AuthManager::registerUser 被调用，用户名:" << username;
    
    // 输入验证
    if (!validateUsername(username)) {
        qDebug() << "AuthManager: 用户名格式验证失败";
        emit registrationFailed("用户名格式无效（3-20个字符，只能包含字母、数字和下划线）");
        return false;
    }
    
    if (!validateEmail(email)) {
        qDebug() << "AuthManager: 邮箱格式验证失败";
        emit registrationFailed("邮箱格式无效");
        return false;
    }
    
    if (!validatePassword(password)) {
        qDebug() << "AuthManager: 密码格式验证失败";
        emit registrationFailed("密码格式无效（至少6个字符）");
        return false;
    }

    // 尝试注册
    qDebug() << "AuthManager: 验证通过，调用 dbManager->registerUser";
    bool success = dbManager->registerUser(username, email, password);
    qDebug() << "AuthManager: dbManager->registerUser 返回结果:" << success;
    
    if (success) {
        qDebug() << "AuthManager: 准备发送 registrationSuccess 信号";
        emit registrationSuccess("注册成功！请登录");
        qDebug() << "AuthManager: registrationSuccess 信号已发送";
    } else {
        qDebug() << "AuthManager: 准备发送 registrationFailed 信号";
        emit registrationFailed("注册失败：用户名或邮箱已存在");
        qDebug() << "AuthManager: registrationFailed 信号已发送";
    }
    
    return success;
}

bool AuthManager::loginUser(const QString &username, const QString &password)
{
    qDebug() << "AuthManager: loginUser 被调用，用户名:" << username;
    if (username.isEmpty() || password.isEmpty()) {
        qDebug() << "AuthManager: 用户名或密码为空";
        emit loginFailed("用户名和密码不能为空");
        return false;
    }

    qDebug() << "AuthManager: 调用 dbManager->loginUser";
    QVariantMap userInfo = dbManager->loginUser(username, password);
    qDebug() << "AuthManager: dbManager 返回结果，isEmpty:" << userInfo.isEmpty();
    
    if (!userInfo.isEmpty()) {
        qDebug() << "AuthManager: 设置登录状态";
        bool isAdmin = userInfo["is_admin"].toBool();
        setLoginStatus(true, 
                      userInfo["username"].toString(),
                      userInfo["email"].toString(),
                      userInfo["id"].toInt(),
                      isAdmin);
        saveLoginState(); // 保存登录状态
        qDebug() << "AuthManager: 发送 loginSuccess 信号，管理员权限:" << isAdmin;
        emit loginSuccess("登录成功！欢迎 " + username);
        qDebug() << "AuthManager: loginSuccess 信号已发送";
        return true;
    } else {
        qDebug() << "AuthManager: 登录失败，发送 loginFailed 信号";
        emit loginFailed("登录失败：用户名或密码错误");
        return false;
    }
}

void AuthManager::logoutUser()
{
    setLoginStatus(false);
    saveLoginState(); // 保存登出状态
    emit logoutSuccess();
}

bool AuthManager::validateEmail(const QString &email)
{
    QRegularExpression emailRegex(R"(^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$)");
    return emailRegex.match(email).hasMatch();
}

bool AuthManager::validatePassword(const QString &password)
{
    return password.length() >= 6;
}

bool AuthManager::validateUsername(const QString &username)
{
    if (username.length() < 3 || username.length() > 20) {
        return false;
    }
    
    QRegularExpression usernameRegex(R"(^[a-zA-Z0-9_]+$)");
    return usernameRegex.match(username).hasMatch();
}

void AuthManager::setLoginStatus(bool loggedIn, const QString &username, const QString &email, int userId, bool isAdmin)
{
    m_isLoggedIn = loggedIn;
    m_currentUser = username;
    m_userEmail = email;
    m_userId = userId;
    m_isAdmin = isAdmin;
    
    emit loginStatusChanged();
}

void AuthManager::saveLoginState()
{
    QString configPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
    QDir().mkpath(configPath);
    
    QSettings settings(configPath + "/auth.ini", QSettings::IniFormat);
    settings.setValue("isLoggedIn", m_isLoggedIn);
    settings.setValue("currentUser", m_currentUser);
    settings.setValue("userEmail", m_userEmail);
    settings.setValue("userId", m_userId);
    settings.setValue("isAdmin", m_isAdmin);
    settings.sync();
}

void AuthManager::loadLoginState()
{
    QString configPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
    QSettings settings(configPath + "/auth.ini", QSettings::IniFormat);
    
    m_isLoggedIn = settings.value("isLoggedIn", false).toBool();
    m_currentUser = settings.value("currentUser", "").toString();
    m_userEmail = settings.value("userEmail", "").toString();
    m_userId = settings.value("userId", -1).toInt();
    m_isAdmin = settings.value("isAdmin", false).toBool();
    
    // 发出状态变化信号
    if (m_isLoggedIn) {
        emit loginStatusChanged();
    }
}

void AuthManager::clearLoginState()
{
    setLoginStatus(false);
    saveLoginState();
    qDebug() << "登录状态已清除";
}